package com.wing.purchase.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.product.service.DynamicService;
import com.wing.purchase.dao.PurchaseRequisitionsDao;
import com.wing.purchase.model.entity.*;
import com.wing.purchase.model.request.PurchaseRequisitionsForm;
import com.wing.purchase.model.response.PurchaseRequisitionsVO;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 采购请购单-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class PurchaseRequisitionsServiceImpl extends ServiceImpl<PurchaseRequisitionsDao, PurchaseRequisitions> implements PurchaseRequisitionsService {

    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private PurchaseRequisitionsDetailService purchaseRequisitionsDetailService;
    @Autowired
    private PurchasePlanCheckService purchasePlanCheckService;
    @Autowired
    private PurchasePlanCheckDetailService purchasePlanCheckDetailService;

    @Override
    @Transactional(readOnly = false)
    public int add(PurchaseRequisitionsForm purchaseRequisitionsForm) {

        //校验
        PurchaseRequisitions purchaseRequisitions =new PurchaseRequisitions();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(PurchaseRequisitions.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(purchaseRequisitionsForm, purchaseRequisitions, copyOptions);

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String code = dynamicService.getMaxCode("receipts_no", "pur_purchase_requisitions");
        String day = simpleDateFormat.format(new Date());
        purchaseRequisitions.setReceiptsNo("PR"+day+code);
        //自动生成的 改成已确认
        if (purchaseRequisitionsForm.getPurchasePlanCheckId()!=null) {
            purchaseRequisitions.setStatus(PurchaseRequisitions.Status.stayAudit);
        }else{
            purchaseRequisitions.setStatus(PurchaseRequisitions.Status.stayConfirm);
        }
        int i = baseMapper.insert(purchaseRequisitions);

        List<PurchasePlanCheckDetail> purchasePlanCheckDetails = new ArrayList<>();
        if(i > 0){
            // 添加请购单明细
            for(PurchaseRequisitionsDetail purchaseRequisitionsDetail :purchaseRequisitionsForm.getPurchaseRequisitionsDetails()){
                //如果是生成的
                if (purchaseRequisitionsDetail.getPlanCheckDetailId()!=null) {
                    //计算剩余的
                    purchaseRequisitionsDetail.setPurchaseRequisitionsId(purchaseRequisitions.getId());
                    PurchasePlanCheckDetail byId = purchasePlanCheckDetailService.getById(purchaseRequisitionsDetail.getPlanCheckDetailId());
                    if (null != purchaseRequisitionsDetail.getQuantity()) {
                        BigDecimal surplusQuantity = byId.getSurplusQuantity();
                        //剩余个数
                        BigDecimal result = surplusQuantity.subtract(purchaseRequisitionsDetail.getQuantity());
                        byId.setUpdateTime(LocalDateTime.now());
                        byId.setSurplusQuantity(result);
                    }
                    purchasePlanCheckDetails.add(byId);
                }
                //手动添加
                else{
                    purchaseRequisitionsDetail.setPurchaseRequisitionsId(purchaseRequisitions.getId());
                    //剩余待发
                    purchaseRequisitionsDetail.setSurplusQuantity(purchaseRequisitionsDetail.getQuantity());
                }
                //设置数量
                purchaseRequisitionsDetail.setSurplusQuantity(purchaseRequisitionsDetail.getQuantity());
            }
            //保存请购单详情
            purchaseRequisitionsDetailService.saveBatch(purchaseRequisitionsForm.getPurchaseRequisitionsDetails());
            //修改数量
            if (CollectionUtil.isNotEmpty(purchasePlanCheckDetails)) {
                purchasePlanCheckDetailService.updateBatchById(purchasePlanCheckDetails);
            }

            // 修改领料单核对
            if(null != purchaseRequisitionsForm.getPurchasePlanCheckId()){
                //查询下边的详情 是否全部发配完毕
                QueryWrapper<PurchasePlanCheckDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("check_id", purchaseRequisitionsForm.getPurchasePlanCheckId());
                queryWrapper.eq("is_deleted", false);
                List<PurchasePlanCheckDetail> list = this.purchasePlanCheckDetailService.list(queryWrapper);
                AtomicReference<Boolean> isOk = new AtomicReference<>(true);
                if (CollectionUtil.isNotEmpty(list)){
                    list.forEach(info->{
                        if (!((info.getSurplusQuantity().compareTo(BigDecimal.ZERO)) ==0)){
                            isOk.set(false);
                        }
                    });
                }
                if (isOk.get()){
                    PurchasePlanCheck purchasePlanCheck = purchasePlanCheckService.getById(purchaseRequisitionsForm.getPurchasePlanCheckId());
                    purchasePlanCheck.setUpdateTime(LocalDateTime.now());
                    purchasePlanCheck.setHasGenerateOrder(true);
                    purchasePlanCheckService.updateById(purchasePlanCheck);
                }
            }
        }
        return i;
    }

    @Override
    @Transactional(readOnly = false)
    public int update(PurchaseRequisitions purchaseRequisitions) {
        if(purchaseRequisitions.getStatus().equals(PurchaseRequisitions.Status.fail)){
            // 审核拒绝状态修改之后将状态修改为待确认
            purchaseRequisitions.setStatus(PurchaseRequisitions.Status.stayConfirm);
        }
        return updateDate(purchaseRequisitions);
    }

    @Override
    public List<PurchaseRequisitionsVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<PurchaseRequisitionsVO> pageList4app(Page page, Map<String, Object> params) {
        List<PurchaseRequisitionsVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public PurchaseRequisitionsVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional(readOnly = false)
    public boolean delete(Long purchaseRequisitionsId) {
        int i = baseMapper.deleteById(purchaseRequisitionsId);
        if(i > 0){
            // 删除明细
            purchaseRequisitionsDetailService.remove(new QueryWrapper<PurchaseRequisitionsDetail>().eq("purchase_requisitions_id", purchaseRequisitionsId));
        }
        return i > 0;
    }

    @Override
    public int confirm(Integer id) {
        PurchaseRequisitions purchaseRequisitions = baseMapper.selectById(id);
        purchaseRequisitions.setStatus(PurchaseRequisitions.Status.stayAudit);
        purchaseRequisitions.setAffirmant(JwtUtils.getLoginUserId());
        return baseMapper.updateById(purchaseRequisitions);
    }

    @Override
    @Transactional(readOnly = false)
    public int audit(PurchaseRequisitions purchaseRequisitions) {
        purchaseRequisitions.setAuditor(JwtUtils.getLoginUserId());
        return updateDate(purchaseRequisitions);
    }

    @Override
    public int close(Integer id) {
        PurchaseRequisitions purchaseRequisitions = baseMapper.selectById(id);
        purchaseRequisitions.setStatus(PurchaseRequisitions.Status.closed);
        return baseMapper.updateById(purchaseRequisitions);
    }

    @Override
    @Transactional(readOnly = false)
    public int finish(Integer id) {
        //修改请购单询价状态
        PurchaseRequisitions purchaseRequisitions = baseMapper.selectById(id);
        purchaseRequisitions.setEnquiryStatus(PurchaseRequisitions.EnquiryStatus.finish);
        int i = baseMapper.updateById(purchaseRequisitions);
        if(i > 0){
            //修改请购单对应的所有的询价单的询价状态
            baseMapper.updateEnquiry(id);
        }
        return i;
    }

    public int updateDate(PurchaseRequisitions purchaseRequisitions){
        int i = baseMapper.updateById(purchaseRequisitions);
        if(i > 0){
            List<PurchaseRequisitionsDetail> addDetails = new ArrayList<>();
            List<PurchaseRequisitionsDetail> updDetails = new ArrayList<>();
            List<Long> delDetails = new ArrayList<>();
            List<Long> ids = new ArrayList<>();
            for(PurchaseRequisitionsDetail purchaseRequisitionsDetail : purchaseRequisitions.getPurchaseRequisitionsDetails()){
                if(null == purchaseRequisitionsDetail.getId()){
                    purchaseRequisitionsDetail.setCreator(JwtUtils.getLoginUserId());
                    purchaseRequisitionsDetail.setCreatorName(JwtUtils.getLoginUsername());
                    purchaseRequisitionsDetail.setModifier(JwtUtils.getLoginUserId());
                    purchaseRequisitionsDetail.setModifierName(JwtUtils.getLoginUsername());
                    purchaseRequisitionsDetail.setPurchaseRequisitionsId(purchaseRequisitions.getId());
                    addDetails.add(purchaseRequisitionsDetail);
                }else{
                    ids.add(purchaseRequisitionsDetail.getId());
                    updDetails.add(purchaseRequisitionsDetail);
                }
            }
            // 查询旧数据
            List<PurchaseRequisitionsDetail> oldDetails = purchaseRequisitionsDetailService.list(new QueryWrapper<PurchaseRequisitionsDetail>().eq("purchase_requisitions_id", purchaseRequisitions.getId()));
            for (PurchaseRequisitionsDetail oldDetail : oldDetails) {
                if(!ids.contains(oldDetail.getId())){
                    delDetails.add(oldDetail.getId());
                }
            }
            if(addDetails.size() > 0){
                purchaseRequisitionsDetailService.saveBatch(addDetails);
            }
            if(updDetails.size() > 0){
                purchaseRequisitionsDetailService.updateBatchById(updDetails);
            }
            if(delDetails.size() > 0){
                purchaseRequisitionsDetailService.removeByIds(delDetails);
            }
        }
        return i;
    }

}
